<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
<link rel="STYLESHEET" href="lib.css" type='text/css' />
<link rel="SHORTCUT ICON" href="../icons/pyfav.png" type="image/png" />
<link rel='start' href='../index.html' title='Python documentation Index' />
<link rel="first" href="lib.html" title='Python library Reference' />
<link rel='contents' href='contents.html' title="Contents" />
<link rel='index' href='genindex.html' title='Index' />
<link rel='last' href='about.html' title='About this document...' />
<link rel='help' href='about.html' title='About this document...' />
<link rel="prev" href="node265.html" />
<link rel="parent" href="module-csv.html" />
<link rel="next" href="module-ConfigParser.html" />
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name='aesop' content='information' />
<title>9.1.5 Examples</title>
</head>
<body>
<div class="navigation">
<div id='top-navigation-panel' xml:id='top-navigation-panel'>
<table align="center" width="100%" cellpadding="0" cellspacing="2">
<tr>
<td class='online-navigation'><a rel="prev" title="9.1.4 writer Objects"
  href="node265.html"><img src='../icons/previous.png'
  border='0' height='32'  alt='Previous Page' width='32' /></a></td>
<td class='online-navigation'><a rel="parent" title="9.1 csv  "
  href="module-csv.html"><img src='../icons/up.png'
  border='0' height='32'  alt='Up one Level' width='32' /></a></td>
<td class='online-navigation'><a rel="next" title="9.2 configparser  "
  href="module-ConfigParser.html"><img src='../icons/next.png'
  border='0' height='32'  alt='Next Page' width='32' /></a></td>
<td align="center" width="100%">Python Library Reference</td>
<td class='online-navigation'><a rel="contents" title="Table of Contents"
  href="contents.html"><img src='../icons/contents.png'
  border='0' height='32'  alt='Contents' width='32' /></a></td>
<td class='online-navigation'><a href="modindex.html" title="Module Index"><img src='../icons/modules.png'
  border='0' height='32'  alt='Module Index' width='32' /></a></td>
<td class='online-navigation'><a rel="index" title="Index"
  href="genindex.html"><img src='../icons/index.png'
  border='0' height='32'  alt='Index' width='32' /></a></td>
</tr></table>
<div class='online-navigation'>
<b class="navlabel">Previous:</b>
<a class="sectref" rel="prev" href="node265.html">9.1.4 Writer Objects</a>
<b class="navlabel">Up:</b>
<a class="sectref" rel="parent" href="module-csv.html">9.1 csv  </a>
<b class="navlabel">Next:</b>
<a class="sectref" rel="next" href="module-ConfigParser.html">9.2 ConfigParser  </a>
</div>
<hr /></div>
</div>
<!--End of Navigation Panel-->

<h2><a name="SECTION0011150000000000000000"></a><a name="csv-examples"></a>
<br>
9.1.5 Examples
</h2>

<p>
The simplest example of reading a CSV file:

<p>
<div class="verbatim"><pre>
import csv
reader = csv.reader(open("some.csv", "rb"))
for row in reader:
    print row
</pre></div>

<p>
Reading a file with an alternate format:

<p>
<div class="verbatim"><pre>
import csv
reader = csv.reader(open("passwd", "rb"), delimiter=':', quoting=csv.QUOTE_NONE)
for row in reader:
    print row
</pre></div>

<p>
The corresponding simplest possible writing example is:

<p>
<div class="verbatim"><pre>
import csv
writer = csv.writer(open("some.csv", "wb"))
writer.writerows(someiterable)
</pre></div>

<p>
Registering a new dialect:

<p>
<div class="verbatim"><pre>
import csv

csv.register_dialect('unixpwd', delimiter=':', quoting=csv.QUOTE_NONE)

reader = csv.reader(open("passwd", "rb"), 'unixpwd')
</pre></div>

<p>
A slightly more advanced use of the reader -- catching and reporting errors:

<p>
<div class="verbatim"><pre>
import csv, sys
filename = "some.csv"
reader = csv.reader(open(filename, "rb"))
try:
    for row in reader:
        print row
except csv.Error, e:
    sys.exit('file %s, line %d: %s' % (filename, reader.line_num, e))
</pre></div>

<p>
And while the module doesn't directly support parsing strings, it can
easily be done:

<p>
<div class="verbatim"><pre>
import csv
for row in csv.reader(['one,two,three']):
    print row
</pre></div>

<p>
The <tt class="module">csv</tt> module doesn't directly support reading and writing
Unicode, but it is 8-bit-clean save for some problems with ASCII NUL
characters.  So you can write functions or classes that handle the
encoding and decoding for you as long as you avoid encodings like
UTF-16 that use NULs.  UTF-8 is recommended.

<p>
<tt class="function">unicode_csv_reader</tt> below is a generator that wraps
<tt class="class">csv.reader</tt> to handle Unicode CSV data (a list of Unicode
strings).  <tt class="function">utf_8_encoder</tt> is a generator that encodes the
Unicode strings as UTF-8, one string (or row) at a time.  The encoded
strings are parsed by the CSV reader, and
<tt class="function">unicode_csv_reader</tt> decodes the UTF-8-encoded cells back
into Unicode:

<p>
<div class="verbatim"><pre>
import csv

def unicode_csv_reader(unicode_csv_data, dialect=csv.excel, **kwargs):
    # csv.py doesn't do Unicode; encode temporarily as UTF-8:
    csv_reader = csv.reader(utf_8_encoder(unicode_csv_data),
                            dialect=dialect, **kwargs)
    for row in csv_reader:
        # decode UTF-8 back to Unicode, cell by cell:
        yield [unicode(cell, 'utf-8') for cell in row]

def utf_8_encoder(unicode_csv_data):
    for line in unicode_csv_data:
        yield line.encode('utf-8')
</pre></div>

<p>
For all other encodings the following <tt class="class">UnicodeReader</tt> and
<tt class="class">UnicodeWriter</tt> classes can be used. They take an additional
<var>encoding</var> parameter in their constructor and make sure that the data
passes the real reader or writer encoded as UTF-8:

<p>
<div class="verbatim"><pre>
import csv, codecs, cStringIO

class UTF8Recoder:
    """
    Iterator that reads an encoded stream and reencodes the input to UTF-8
    """
    def __init__(self, f, encoding):
        self.reader = codecs.getreader(encoding)(f)

    def __iter__(self):
        return self

    def next(self):
        return self.reader.next().encode("utf-8")

class UnicodeReader:
    """
    A CSV reader which will iterate over lines in the CSV file "f",
    which is encoded in the given encoding.
    """

    def __init__(self, f, dialect=csv.excel, encoding="utf-8", **kwds):
        f = UTF8Recoder(f, encoding)
        self.reader = csv.reader(f, dialect=dialect, **kwds)

    def next(self):
        row = self.reader.next()
        return [unicode(s, "utf-8") for s in row]

    def __iter__(self):
        return self

class UnicodeWriter:
    """
    A CSV writer which will write rows to CSV file "f",
    which is encoded in the given encoding.
    """

    def __init__(self, f, dialect=csv.excel, encoding="utf-8", **kwds):
        # Redirect output to a queue
        self.queue = cStringIO.StringIO()
        self.writer = csv.writer(self.queue, dialect=dialect, **kwds)
        self.stream = f
        self.encoder = codecs.getincrementalencoder(encoding)()

    def writerow(self, row):
        self.writer.writerow([s.encode("utf-8") for s in row])
        # Fetch UTF-8 output from the queue ...
        data = self.queue.getvalue()
        data = data.decode("utf-8")
        # ... and reencode it into the target encoding
        data = self.encoder.encode(data)
        # write to the target stream
        self.stream.write(data)
        # empty queue
        self.queue.truncate(0)

    def writerows(self, rows):
        for row in rows:
            self.writerow(row)
</pre></div>

<div class="navigation">
<div class='online-navigation'>
<p></p><hr />
<table align="center" width="100%" cellpadding="0" cellspacing="2">
<tr>
<td class='online-navigation'><a rel="prev" title="9.1.4 writer Objects"
  href="node265.html"><img src='../icons/previous.png'
  border='0' height='32'  alt='Previous Page' width='32' /></a></td>
<td class='online-navigation'><a rel="parent" title="9.1 csv  "
  href="module-csv.html"><img src='../icons/up.png'
  border='0' height='32'  alt='Up one Level' width='32' /></a></td>
<td class='online-navigation'><a rel="next" title="9.2 configparser  "
  href="module-ConfigParser.html"><img src='../icons/next.png'
  border='0' height='32'  alt='Next Page' width='32' /></a></td>
<td align="center" width="100%">Python Library Reference</td>
<td class='online-navigation'><a rel="contents" title="Table of Contents"
  href="contents.html"><img src='../icons/contents.png'
  border='0' height='32'  alt='Contents' width='32' /></a></td>
<td class='online-navigation'><a href="modindex.html" title="Module Index"><img src='../icons/modules.png'
  border='0' height='32'  alt='Module Index' width='32' /></a></td>
<td class='online-navigation'><a rel="index" title="Index"
  href="genindex.html"><img src='../icons/index.png'
  border='0' height='32'  alt='Index' width='32' /></a></td>
</tr></table>
<div class='online-navigation'>
<b class="navlabel">Previous:</b>
<a class="sectref" rel="prev" href="node265.html">9.1.4 Writer Objects</a>
<b class="navlabel">Up:</b>
<a class="sectref" rel="parent" href="module-csv.html">9.1 csv  </a>
<b class="navlabel">Next:</b>
<a class="sectref" rel="next" href="module-ConfigParser.html">9.2 ConfigParser  </a>
</div>
</div>
<hr />
<span class="release-info">Release 2.5.1, documentation updated on 18th April, 2007.</span>
</div>
<!--End of Navigation Panel-->
<address>
See <i><a href="about.html">About this document...</a></i> for information on suggesting changes.
</address>
</body>
</html>
